package design.pattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 代理类  皮包公司
 */
public class DBQueryProxy implements IDBQuery {
	private DBQuery real=null; 
	@Override
	public String request() throws InterruptedException {
		//在真正需要的时候 ，才创建真实对象，创建过程可能很慢
		long beginTime = System.currentTimeMillis();
		if(real==null) {
			//干活的类去做的
			real = new DBQuery();
		}
		String request = real.request();
		long endTime = System.currentTimeMillis();
		System.out.println("查询数据库耗时："+(endTime-beginTime)+"毫秒");
		return request;
	}


	public static void main(String[] args) throws InterruptedException {
		//DBQueryProxy dbQueryProxy = new DBQueryProxy();
		//System.out.println(dbQueryProxy.request());

		//		//动态代理 cglib
		IDBQuery o = (IDBQuery)Proxy.newProxyInstance(IDBQuery.class.getClassLoader(), new Class[]{IDBQuery.class}, new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				System.out.println("动态代理..........");
				long beginTime = System.currentTimeMillis();
				String request = new DBQuery().request();
				long endTime = System.currentTimeMillis();
				System.out.println("查询数据库耗时："+(endTime-beginTime)+"毫秒");
				return request;
			}
		});
		System.out.print(o.request());

	}
}
